// utils/converter.js - 数据转换工具

/**
 * ArrayBuffer转16进制字符串
 * @param {ArrayBuffer} buffer ArrayBuffer数据
 * @returns {string} 16进制字符串
 */
export function ab2hex(buffer) {
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2);
    }
  );
  return hexArr.join('');
}

/**
 * 16进制字符串转ArrayBuffer
 * @param {string} hexStr 16进制字符串
 * @returns {ArrayBuffer} ArrayBuffer数据
 */
export function hex2ab(hexStr) {
  if (hexStr.length % 2 === 1) {
    hexStr = '0' + hexStr;
  }
  return new Uint8Array(
    Array.prototype.map.call(
      hexStr.match(/[\da-f]{2}/ig),
      hex => parseInt(hex, 16)
    )
  ).buffer;
}

/**
 * ArrayBuffer转Uint8Array
 * @param {ArrayBuffer} buffer ArrayBuffer数据
 * @returns {Array} Uint8Array数据
 */
export function ab2u8(buffer) {
  return Array.prototype.slice.call(new Uint8Array(buffer));
}

/**
 * Uint8Array转ArrayBuffer
 * @param {Array} u8array Uint8Array数据
 * @returns {ArrayBuffer} ArrayBuffer数据
 */
export function u82ab(u8array) {
  const arrayBuffer = new ArrayBuffer(u8array.length);
  const dataView = new DataView(arrayBuffer);
  u8array.forEach((u8, index) => {
    dataView.setUint8(index, u8);
  });
  return arrayBuffer;
}

/**
 * Uint8Array转16进制字符串
 * @param {Array} u8array Uint8Array数据
 * @returns {string} 16进制字符串
 */
export function u82hex(u8array) {
  return Array.prototype.map.call(u8array, function (bit) {
    return ('00' + bit.toString(16)).slice(-2);
  }).join('');
}

/**
 * 16进制字符串转Uint8Array
 * @param {string} hexStr 16进制字符串
 * @returns {Array} Uint8Array数据
 */
export function hex2u8(hexStr) {
  if (hexStr.length % 2 === 1) {
    hexStr = '0' + hexStr;
  }
  return Array.prototype.map.call(
    hexStr.match(/[\da-f]{2}/ig), 
    hex => parseInt(hex, 16)
  );
}

/**
 * 字符串转十六进制
 * @param {string} str 要转换的字符串
 * @returns {string} 十六进制字符串
 */
export function strToHex(str) {
  let hex = '';
  for (let i = 0; i < str.length; i++) {
    hex += ('00' + str.charCodeAt(i).toString(16)).slice(-2);
  }
  return hex;
}

/**
 * 十六进制转字符串
 * @param {string} hex 十六进制字符串
 * @returns {string} 解码后的字符串
 */
export function hexToStr(hex) {
  let str = '';
  for (let i = 0; i < hex.length; i += 2) {
    str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  }
  return str;
}

export default {
  ab2hex,
  hex2ab,
  ab2u8,
  u82ab,
  u82hex,
  hex2u8,
  strToHex,
  hexToStr
};